package org.hepeng.commons.spring.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * @author he peng
 */

@Deprecated
public class SecurityContextWrapper implements SecurityContext {

    private SecurityContext delegate;

    public SecurityContextWrapper(SecurityContext securityContext) {
        this.delegate = securityContext;
        if (Objects.nonNull(this.delegate)) {
            AuthenticationWrapper authWrapper = new AuthenticationWrapper(this.delegate.getAuthentication(), null);
            setAuthentication(authWrapper);
            SecurityContextHolder.setContext(this);
        }
    }

    @Override
    public Authentication getAuthentication() {
        return delegate.getAuthentication();
    }

    @Override
    public void setAuthentication(Authentication authentication) {
        Authentication oldAuth = delegate.getAuthentication();
        if (Objects.nonNull(oldAuth) && oldAuth instanceof AuthenticationWrapper) {
            delegate.setAuthentication(null);
            delegate.setAuthentication(authentication);
        } else {
            delegate.setAuthentication(authentication);
        }
    }

    @Override
    public String toString() {
        return "SecurityContextWrapper{" +
                "delegate=" + delegate +
                '}';
    }
}
